package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.EventType;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.User;
import com.sl.au.entity.UserEventTypeBindInfo;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.HierarchyService;
import com.sl.au.service.UserEventTypeBindInfoService;
import com.sl.au.service.UserService;
import com.sl.utils.MsgHelper;

@RestController
@RequestMapping("/ui/userEventTypeBind")
public class UserEventTypeBindInfoController extends BaseController {

	@Autowired
	private EventTypeService eventTypeService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserEventTypeBindInfoService userEventTypeBindInfoService;
	@Autowired
	private HierarchyService hierarchyService;

	@RequestMapping("/findAllBind/{typeId}")
	public MsgHelper findAllbBind(@PathVariable("typeId") String typeId, String con) {
		String key = typeId;
		List<User> users = null;
		if (StringUtils.hasText(con)) {
			users = userService.findUsersBindEventTypeByKeyAndCon(0, Integer.MAX_VALUE, key, con);

		} else {
			users = userService.findUsersBindEventTypeOnlyKey(0, Integer.MAX_VALUE, key);

		}
		return MsgHelper.success().put("users", users);
	}

	@RequestMapping("/findAllUnbind/{typeId}")
	public MsgHelper findAllUnbind(@PathVariable("typeId") String typeId, String con) {
		String key = typeId;
		List<User> users = null;
		if (StringUtils.hasText(con)) {
			users = userService.findUsersUnbindEventTypeByKeyAndCon(0, Integer.MAX_VALUE, key, con);

		} else {
			users = userService.findUsersUnbindEventTypeOnlyKey(0, Integer.MAX_VALUE, key);

		}
		return MsgHelper.success().put("users", users);
	}

	@RequestMapping("/checkHierarchy/{groupName}")
	public MsgHelper checkHierarchy(@PathVariable("groupName") String groupName) {
		List<Hierarchy> list = hierarchyService.getRepository().findByGroupName(groupName);
		if (list == null || list.size() == 0) {
			return MsgHelper.failed();
		} else {
			return MsgHelper.success().put("list", list);
		}
	}

	@RequestMapping("/unbind/{userIds}/{typeIds}")
	public MsgHelper unbind(@PathVariable("userIds") String userIds, @PathVariable("typeIds") String typeIds) {
		// 去掉最后一个逗号
		typeIds = typeIds.substring(0, typeIds.length() - 1);
		userIds = userIds.substring(0, userIds.length() - 1);
		String[] typeIdArr = typeIds.split(",");
		String[] userIdArr = userIds.split(",");
		int i = 0;
		int by = typeIdArr.length * userIdArr.length;
		MsgHelper helper = MsgHelper.success();
		for (String userId : userIdArr) {

			for (String typeId : typeIdArr) {
				UserEventTypeBindInfo info = userEventTypeBindInfoService.findByUserAndType(userId, typeId);
				if (info != null) {

					userEventTypeBindInfoService.getRepository().delete(info);
					++i;
				}

			}
		}

		helper.put("msg", "成功解除 " + i + " 条绑定记录,过滤掉 " + (by - i) + " 条未绑定信息");

		return helper;
	}

	@RequestMapping("/bind/{userIds}/{typeIds}")
	public MsgHelper bind(@PathVariable("userIds") String userIds, @PathVariable("typeIds") String typeIds) {
		// 去掉最后一个逗号
		typeIds = typeIds.substring(0, typeIds.length() - 1);
		userIds = userIds.substring(0, userIds.length() - 1);
		String[] typeIdArr = typeIds.split(",");
		String[] userIdArr = userIds.split(",");
		int i = 0;
		int by = typeIdArr.length * userIdArr.length;
		MsgHelper helper = MsgHelper.success();
		for (String userId : userIdArr) {

			for (String typeId : typeIdArr) {
				UserEventTypeBindInfo info = userEventTypeBindInfoService.findByUserAndType(userId, typeId);
				// 如果之前已经被绑定,不需要再绑定
				if (info == null) {
					info = new UserEventTypeBindInfo();
					info.setUser(userService.getRepository().findOne(userId));
					info.setEventType(eventTypeService.getRepository().findOne(typeId));
					userEventTypeBindInfoService.getRepository().save(info);
					++i;
				}

			}
		}

		helper.put("msg", "成功绑定 " + i + " 条记录,过滤掉 " + (by - i) + " 条已绑定信息");

		return helper;
	}

	@RequestMapping(value = "/showBindUsers", method = RequestMethod.GET)
	public Map<String, Object> showBindUsers(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 事件类型的id
		String con = request.getParameter("con");

		List<User> users = null;
		int count = 0;

		if ("0".equals(key)) {// 查询所有
			if (StringUtils.hasText(con)) {
				users = userService.findUsersBindEventTypeOnlyCon(start, length, con);
				count = userService.findUsersCountBindEventTypeOnlyCon(con);
			} else {
				users = userService.findUsersBindEventTypeNone(start, length);
				count = userService.findUsersCountBindEventTypeNone(start, length);
			}
		} else {// 查询指定类型
			if (StringUtils.hasText(con)) {
				users = userService.findUsersBindEventTypeByKeyAndCon(start, length, key, con);
				count = userService.findUsersCountBindEventTypeByKeyAndCon(key, con);
			} else {
				users = userService.findUsersBindEventTypeOnlyKey(start, length, key);
				count = userService.findUsersCountBindEventTypeOnlyKey(key);
			}
		}
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/showUnbindUsers", method = RequestMethod.GET)
	public Map<String, Object> showUnbindUsers(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 事件类型的id
		String con = request.getParameter("con");

		List<User> users = null;
		int count = 0;

		if ("0".equals(key)) {// 查询所有
			if (StringUtils.hasText(con)) {
				users = userService.findUsersUnbindEventTypeOnlyCon(start, length, con);
				count = userService.findUsersCountUnbindEventTypeOnlyCon(con);
			} else {
				users = userService.findUsersUnbindEventTypeNone(start, length);
				count = userService.findUsersCountUnbindEventTypeNone();
			}
		} else {// 查询指定类型
			if (StringUtils.hasText(con)) {
				users = userService.findUsersUnbindEventTypeByKeyAndCon(start, length, key, con);
				count = userService.findUsersCountUnbindEventTypeByKeyAndCon(key, con);
			} else {
				users = userService.findUsersUnbindEventTypeOnlyKey(start, length, key);
				count = userService.findUsersCountUnbindEventTypeOnlyKey(key);
			}
		}
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/initTypeTree", method = RequestMethod.GET)
	public Map<String, Object> getAllNodes(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<EventType> node = eventTypeService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = eventTypeService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		modelAndView = createLayoutView("userEventType/index");
		return modelAndView;
	}
}
